//
//  YZNetWorkRequestManager.m
//  VET
//
//  Created by YZ on 2018/7/17.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZNetWorkRequestManager.h"
#import <AFNetworking/AFNetworking.h>

@interface YZNetWorkRequestManager()

@property (nonatomic, strong) AFHTTPSessionManager *manager;

@end

@implementation YZNetWorkRequestManager

SingletonM

- (instancetype)init
{
    if (self = [super init]) {
        self.manager = [AFHTTPSessionManager manager];
        
        AFJSONRequestSerializer *reqSerializer = [AFJSONRequestSerializer serializer];
        [reqSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [reqSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        // 超时时间
        self.manager.requestSerializer.timeoutInterval = 30;
        // 请求压缩方式
        [self.manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
        [self.manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
        self.manager.requestSerializer = reqSerializer;
        
        AFJSONResponseSerializer *resSerializer = [AFJSONResponseSerializer serializer];
        [resSerializer setReadingOptions:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers];
        resSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", nil];
        self.manager.responseSerializer = resSerializer;
    }
    return self;
}

/**
 多图片上传
 */
- (void)reqestUploadImgsWithApi:(NSString*)api params:(NSDictionary *)params imgs:(NSArray<UIImage *> *)images name:(NSString *)name withHeaders:(NSDictionary *)headers success:(YZNetworkCompletionSuccessBlock)successBlock fail:(YZNetworkCompletionFailBlock)failBlock
{
//    params = [self configParamsWithParams:params];
    [self configHeadersWithHeaders:headers];
    NSString *url = [NSString stringWithFormat:@"%@%@",[YZNetworkConfig getCurrentDomain],api];
    [self.manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        
        for (int i = 0; i < images.count; i++) {
            NSData *imageData = UIImageJPEGRepresentation(images[i], .5);
            NSString *fileName = [NSString  stringWithFormat:@"%@_%d.jpg", dateString,i];
            [formData appendPartWithFileData:imageData name:name.length > 0?name:[NSString stringWithFormat:@"%d",i] fileName:fileName mimeType:@"image/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (successBlock) {
            successBlock(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failBlock) {
            failBlock(error);
        }
    }];
}

/**
 本地视频上传
 */
- (void)reqestUploadVideoWithApi:(NSString*)api params:(NSDictionary *)params videoPath:(NSString *)videoPath name:(NSString *)name withHeaders:(NSDictionary *)headers success:(YZNetworkCompletionSuccessBlock)successBlock fail:(YZNetworkCompletionFailBlock)failBlock{
    params = [self configParamsWithParams:params];
    [self configHeadersWithHeaders:headers];
    NSString *url = [NSString stringWithFormat:@"%@%@",[YZNetworkConfig getCurrentDomain],api];
    [self.manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString  stringWithFormat:@"%@.mp4", dateString];
        NSData *fileData = [NSData dataWithContentsOfFile:videoPath];
        [formData appendPartWithFileData:fileData name:name?name:@"video" fileName:fileName mimeType:@"video/mp4"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (successBlock) {
            successBlock(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failBlock) {
            failBlock(error);
        }
    }];
    
}
/**
 视频上传
 */
- (void)reqestUploadVideoWithApi:(NSString*)api params:(NSDictionary *)params videoUrl:(NSURL *)videoUrl name:(NSString *)name withHeaders:(NSDictionary *)headers success:(YZNetworkCompletionSuccessBlock)successBlock fail:(YZNetworkCompletionFailBlock)failBlock
{
    params = [self configParamsWithParams:params];
    [self configHeadersWithHeaders:headers];
    NSString *url = [NSString stringWithFormat:@"%@%@",[YZNetworkConfig getCurrentDomain],api];
    [self.manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString  stringWithFormat:@"%@.mp4", dateString];
        NSData *fileData = [NSData dataWithContentsOfURL:videoUrl];
        [formData appendPartWithFileData:fileData name:name?name:@"video" fileName:fileName mimeType:@"video/mp4"];

    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (successBlock) {
            successBlock(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failBlock) {
            failBlock(error);
        }
    }];
}


/**
 post请求
 */
- (void)requestPostWithApi:(NSString*)api params:(NSDictionary *)params withHeaders:(NSDictionary *)headers success:(YZNetworkCompletionSuccessBlock)successBlock fail:(YZNetworkCompletionFailBlock)failBlock
{
    params = [self configParamsWithParams:params];
    [self configHeadersWithHeaders:headers];
    NSString *url = [NSString stringWithFormat:@"%@%@",[YZNetworkConfig getCurrentDomain],api];
    [self.manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (successBlock) {
            successBlock(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failBlock) {
            failBlock(error);
        }
    }];
}

/**
get请求
 */
- (void)requestGetWithApi:(NSString*)api params:(NSDictionary *)params withHeaders:(NSDictionary *)headers success:(YZNetworkCompletionSuccessBlock)successBlock fail:(YZNetworkCompletionFailBlock)failBlock
{
    params = [self configParamsWithParams:params];
    [self configHeadersWithHeaders:headers];
    NSString *url = [NSString stringWithFormat:@"%@%@",[YZNetworkConfig getCurrentDomain],api];
    NSLog(@"url:%@",url);
    [self.manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (successBlock) {
            successBlock(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failBlock) {
            failBlock(error);
        }
    }];
}

- (void)configHeadersWithHeaders:(NSDictionary *)headers
{
    NSMutableDictionary *generalHeaders = [NSMutableDictionary dictionaryWithDictionary:[YZNetworkConfig getGeneralParams]];
    NSLog(@"================Headers=====================")
    NSLog(@"%@",generalHeaders);
    [generalHeaders addEntriesFromDictionary:headers];
    for (NSString *key in generalHeaders.allKeys) {
        [self.manager.requestSerializer setValue:generalHeaders[key] forHTTPHeaderField:key];
    }
}

- (NSDictionary *)configParamsWithParams:(NSDictionary *)params
{
    NSLog(@"=================Params====================")
    NSLog(@"%@",params);
    return params;
}

@end
